package tcp

import (
	"net"
)

type Server struct {
	*sessionHub
	srv *net.TCPListener
}

func NewServer(initializer func(pipe Pipeline)) *Server {
	return &Server{
		sessionHub: NewSessionHub(initializer),
	}
}

func (s *Server) ListenAndServe(addr string) error {
	tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
	if err != nil {
		return err
	}
	return s.listenAndServe(tcpAddr)
}

func (s *Server) listenAndServe(tcpAddr *net.TCPAddr) error {
	srv, err := net.ListenTCP("tcp", tcpAddr)
	if err != nil {
		return err
	}
	s.srv = srv
	for true {
		tcpConn, errAcc := srv.AcceptTCP()

		if errAcc != nil {
			return errAcc
		}
		s.GetSession(*tcpConn).WatchRead()
	}
	return nil
}

func (s *Server) Close() {
	if s.srv != nil {
		_ = s.srv.Close()
	}
}
